package server;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.Future;

import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

public class Get {
	private ArrayList<Future> arFuture = new ArrayList<Future>();
	private ArrayList<String> arDomain = new ArrayList<String>();
	private URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();
	public Get(String str,HashMap<String,String> listGoogle,String[] arr)
	{	
		String query="";
		try {
			query = URLDecoder.decode(str,"UTF-8").trim().replaceAll("[ ]+", "+");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		for (String key : listGoogle.keySet()) {
			
			if(listGoogle.get(key).equals("www.bing.com"))
			{
				try {
					URL url = new URL("http://"+listGoogle.get(key)+"/search?q="+query+"&qs=n&form=QBRE&pq=abc&sc=8-6&sp=-1&sk=");
					arFuture.add(fetcher.fetchAsync(url));
					arDomain.add(listGoogle.get(key));
				} catch (MalformedURLException e) {
					e.printStackTrace();
				}
	            
			} else {
				try {
					URL url = new URL("https://"+listGoogle.get(key)+"/search?sclient=psy-ab&site=&source=hp&q="+query+"&btnG=T%C3%ACm+ki%E1%BA%BFm");
					arFuture.add(fetcher.fetchAsync(url));
					
					arDomain.add(listGoogle.get(key));
				} catch (MalformedURLException e) {
					e.printStackTrace();
				}
			}
        }
		
		for (int i = 0; i < arFuture.size(); i++) {
			if(arDomain.get(i).equals("www.bing.com"))
			{
				new GetBing(arFuture.get(i),str,arDomain.get(i),i,arr);
			} else {
				new GetContent(arFuture.get(i),str,arDomain.get(i),i,arr);
			}
		}
	}
}
